import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';

class StorageService {
  static final StorageService _instance = StorageService._internal();
  factory StorageService() => _instance;
  StorageService._internal();

  static const String _messagesKey = 'live_messages';
  static const String _keywordsKey = 'filter_keywords';
  static const String _roomIdKey = 'last_room_id';
  static const int _maxStoredMessages = 1000;
  static const String _exactMatchKey = 'exact_match';
  static const String _autoPrintKey = 'auto_print';
  static const String _printerDeviceKey = 'printer_device';

  // 保存自动打印设置
  Future<void> saveAutoPrint(bool autoPrint) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.setBool(_autoPrintKey, autoPrint);
    } catch (e) {
      print('保存自动打印设置错误: $e');
    }
  }
  
  // 加载自动打印设置
  Future<bool> loadAutoPrint() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      return prefs.getBool(_autoPrintKey) ?? false;
    } catch (e) {
      print('加载自动打印设置错误: $e');
      return false;
    }
  }
  
  // 保存打印机设备信息
  Future<void> savePrinterDevice(Map<String, dynamic> deviceInfo) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.setString(_printerDeviceKey, json.encode(deviceInfo));
    } catch (e) {
      print('保存打印机设备信息错误: $e');
    }
  }
  
  // 加载打印机设备信息
  Future<Map<String, dynamic>?> loadPrinterDevice() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final deviceJson = prefs.getString(_printerDeviceKey);
      if (deviceJson != null) {
        return json.decode(deviceJson);
      }
    } catch (e) {
      print('加载打印机设备信息错误: $e');
    }
    return null;
  }

  Future<bool> loadExactMatch() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      return prefs.getBool(_exactMatchKey) ?? false;
    } catch (e) {
      print('加载精准匹配设置错误: $e');
      return false;
    }
  }
  
  Future<void> saveExactMatch(bool exactMatch) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.setBool(_exactMatchKey, exactMatch);
    } catch (e) {
      print('保存精准匹配设置错误: $e');
    }
  }

  Future<void> saveMessages(List<Map<String, dynamic>> messages) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final messagesJson = messages.map((msg) => json.encode(msg)).toList();
      await prefs.setStringList(_messagesKey, messagesJson.take(_maxStoredMessages).toList());
    } catch (e) {
      debugPrint('保存消息失败: $e');
    }
  }

  Future<List<Map<String, dynamic>>> loadMessages() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final messagesJson = prefs.getStringList(_messagesKey) ?? [];
      return messagesJson.map((jsonStr) {
        try {
          return Map<String, dynamic>.from(json.decode(jsonStr));
        } catch (e) {
          return <String, dynamic>{};
        }
      }).where((msg) => msg.isNotEmpty).toList();
    } catch (e) {
      debugPrint('加载消息失败: $e');
      return [];
    }
  }

  Future<void> saveKeywords(List<String> keywords) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.setString(_keywordsKey, keywords.join('#'));
    } catch (e) {
      debugPrint('保存关键词失败: $e');
    }
  }

  Future<List<String>> loadKeywords() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final keywordsStr = prefs.getString(_keywordsKey) ?? '';
      return keywordsStr.split('#').where((k) => k.isNotEmpty).toList();
    } catch (e) {
      debugPrint('加载关键词失败: $e');
      return [];
    }
  }

  Future<void> saveLastRoomId(String roomId) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.setString(_roomIdKey, roomId);
    } catch (e) {
      debugPrint('保存房间ID失败: $e');
    }
  }

  Future<String?> loadLastRoomId() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      return prefs.getString(_roomIdKey);
    } catch (e) {
      debugPrint('加载房间ID失败: $e');
      return null;
    }
  }

  Future<void> clearMessages() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.remove(_messagesKey);
    } catch (e) {
      debugPrint('清空消息失败: $e');
    }
  }

  Future<void> exportMessages(List<Map<String, dynamic>> messages) async {
    try {
      final exportData = {
        'export_time': DateTime.now().toIso8601String(),
        'total_messages': messages.length,
        'messages': messages,
      };
      
      final exportJson = json.encode(exportData);
      // 这里可以扩展为保存到文件或分享
      debugPrint('导出数据: $exportJson');
    } catch (e) {
      debugPrint('导出消息失败: $e');
    }
  }
}